package com.huwaiwai001.netty.nio;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author 歪大哥😁
 * @date 2020-07-07.
 */
public class FileChannelCopier {


    public static void main(String[] args) throws Exception{

        String srcPath = "/Users/kathy/studyCode/common/src/main/java/com/huwaiwai001/netty/nio/file01.txt";
        String targetPath = "/Users/kathy/studyCode/common/src/main/java/com/huwaiwai001/netty/nio/file01_back.txt";


        File srcFile = new File(srcPath);
        File targetFile = new File(targetPath);

        // 创建一个输出流
        try (FileInputStream fileInputStream = new FileInputStream(srcFile);
             FileOutputStream fileOutputStream = new FileOutputStream(targetFile)) {
            // 通过输出流 获取文件channel
            FileChannel channel = fileInputStream.getChannel();
            // 创建一个缓冲区
            ByteBuffer byteBuffer = ByteBuffer.allocate((int) srcFile.length());
            // 1.从channel里面读取数据 写入buffer
            channel.read(byteBuffer);
            // 2.从buffer读取写入的数据
            // 要切换读模式 写入到输出流中
            byteBuffer.flip();
            // 3.用byte数组接收数据
            FileChannel channel1 = fileOutputStream.getChannel();
                channel1.write(byteBuffer);
        }

    }


}
